import { Popup, Picker } from "vant";
// import Hybrid from "@/components/uzone-hybrid";
import keyMap from "@/config/key-map";
import {
  validateEmail,
  validateMobile,
  validateAddress,
} from "@/libs/validate";
// import ubt from "@/service/ubt";
import MixinValidateForm from "@/service/mixin-validate-form";
import NavBar from "../components/navBar1";
import Region from "../../../../static/region.json";
import Province from "../../../../static/province.json";
import City from "../../../../static/city.json";
import doFaceButton from "@/components/doFaceButton";

export default {
  name: "personal-information",
  components: {
    NavBar,
    Popup,
    Picker,
    doFaceButton,
  },
  mixins: [MixinValidateForm],
  data() {
    return {
      productId: "",
      readonly: false,
      instalment: false,
      form: {
        region: "", // 地区
        province: "", // 省
        city: "", // 城市
        address: "", // 详细地址
        civilStatus: "", // 婚姻状况
        // childrenNumber: '', // 子女个数
        education: "", // 教育水平
        // religion: '', // 宗教
        // salary: '',// 月收入
        email: "",
        phone: "",
        socialAccountType: "",
        socialAccount: "",
      },
      status: {
        identity: null,
        personal: null,
        work: null,
        contact: null,
        additional: null,
      },
      regionData: [],
      provinceData: [],
      cityData: [],
      maritalData: keyMap.maritalStatus,
      childData: keyMap.child,
      educationData: keyMap.education,
      incomeData: keyMap.income,
      religionData: keyMap.religionData,
      socialAccountData: keyMap.socialAccountData,
      isVisibleChooseRegion: false,
      isVisibleChooseRegionP: false,
      isVisibleChooseProvince: false,
      isVisibleChooseProvinceP: false,
      isVisibleChooseCity: false,
      isVisibleChooseCityP: false,
      isVisibleChooseMarital: false,
      isVisibleChooseMaritalP: false,
      isVisibleChooseChild: false,
      isVisibleChooseChildP: false,
      isVisibleChooseEducation: false,
      isVisibleChooseEducationP: false,
      isVisibleChooseIncome: false,
      isVisibleChooseIncomeP: false,
      isVisibleChooseReligion: false,
      isVisibleChooseReligionP: false,
      isVisibleChooseSocialAccountType: false,
      isVisibleChooseSocialAccountTypeP: false,
      btnName: this.$t("next"),
      disabledBtn: false,
      pageTrackerInfo: {
        page: 'personalInfo',
        startTime: new Date().getTime()
      }
    };
  },
  computed: {
    btnCanSubmit() {
      // const { region, province, city, address, civilStatus, childrenNumber, education, email, phone, religion, socialAccountType, socialAccount } = this.form;
      // return !region || !province || !city || !address || !civilStatus || !childrenNumber || !education || !email || !phone || !religion || !socialAccountType || !socialAccount;

      // const { region, province, city, address, civilStatus, childrenNumber, education, phone } = this.form;
      // return !region || !province || !city || !address || !civilStatus || !childrenNumber || !education || !phone;

      const { region, province, city, address, civilStatus, education, phone } =
        this.form;
      return (
        !region ||
        !province ||
        !city ||
        !address ||
        !civilStatus ||
        !education ||
        !phone
      );
    },
  },
  methods: {
    // TODO
    handleBlurCheck(e, type = "") {
      // 校验规则提前
      const dom = e.target;
      setTimeout(() => {
        const val = dom.value;
        const inputList = ['phone', 'address']
        if (inputList.includes(type)) {
          if ((type === 'phone' && !validateMobile(val)) || (type === 'address' && !validateAddress(val))) {
            this.markInputNew([type]);
          } else {
            this.removeMarkClick([type]);
          }
          return
        }
        if (!val) {
          this.markEle(dom);
        }
      }, 0);
    },
    /**
     * 获取省数据
     */
    getProvinceData() {
      const region = this.form.region;
      const regionObj = Region.region.filter((item) => item.region === region);
      if (regionObj && regionObj.length >= 1) {
        const regionId = regionObj[0].RegionId;
        this.provinceData = Province.province.filter(
          (item) => item.RegionId === regionId
        );
      }
    },
    /**
     * 获取城市数据
     */
    getCityData() {
      // const region = this.form.region;
      const province = this.form.province;
      const provinceObj = Province.province.filter(
        (item) => item.Province === province
      );
      const provinceId = provinceObj[0].ProvinceId;
      this.cityData = City.city.filter(
        (item) => item.ProvinceId === provinceId
      );
    },
    /**
     * 显示地区选择框
     */
    showChooseRegion() {
      this.isVisibleChooseRegionP = true;
      setTimeout(() => {
        this.isVisibleChooseRegion = true;
      }, 100);
    },
    /**
     * 显示省选择框
     */
    showChooseProvince() {
      this.isVisibleChooseProvinceP = true;
      setTimeout(() => {
        this.isVisibleChooseProvince = true;
      }, 100);
    },
    /**
     * 显示城市选择框
     */
    showChooseCity() {
      this.isVisibleChooseCityP = true;
      setTimeout(() => {
        this.isVisibleChooseCity = true;
      }, 100);
    },
    /**
     * 选择地区
     */
    chooseRegion(val) {
      const form = this.form;
      if (form.region !== val.region) {
        form.region = val.region;
        form.province = "";
        form.city = "";
        this.getProvinceData();
        this.showChooseProvince();
      }
      this.isVisibleChooseRegion = false;
      this.isVisibleChooseRegionP = false;
    },
    /**
     * 选择省
     */
    chooseProvince(val) {
      const form = this.form;
      if (form.province !== val.Province) {
        form.province = val.Province;
        form.city = "";
        this.getCityData();
        this.showChooseCity();
      }
      this.isVisibleChooseProvince = false;
      this.isVisibleChooseProvinceP = false;
    },
    /**
     * 选择城市
     */
    chooseCity(val) {
      this.form.city = val.TownCity;
      this.isVisibleChooseCity = false;
      this.isVisibleChooseCityP = false;
    },
    /**
     * 显示选择婚姻状况
     */
    showChooseMarital() {
      this.isVisibleChooseMaritalP = true;
      setTimeout(() => {
        this.isVisibleChooseMarital = true;
      }, 100);
    },
    /**
     * 选择婚姻状况
     */
    chooseMarital(val) {
      this.form.civilStatus = val.CivilStatus;
      this.isVisibleChooseMarital = false;
      this.isVisibleChooseMaritalP = false;
    },
    /**
     * 显示选择子女个数
     */
    showChooseChild() {
      this.isVisibleChooseChildP = true;
      setTimeout(() => {
        this.isVisibleChooseChild = true;
      }, 100);
    },
    /**
     * 选择子女个数
     */
    chooseChild(val) {
      this.form.childrenNumber = val.name;
      this.isVisibleChooseChild = false;
      this.isVisibleChooseChildP = false;
    },
    /**
     * 显示选择教育水平
     */
    showChooseEducation() {
      this.isVisibleChooseEducationP = true;
      setTimeout(() => {
        this.isVisibleChooseEducation = true;
      }, 100);
    },
    /**
     * 选择教育水平
     */
    chooseEducation(val) {
      this.form.education = val;
      this.isVisibleChooseEducation = false;
      this.isVisibleChooseEducationP = false;
    },
    /**
     * 显示选择月收入
     */
    showChooseIncome() {
      this.isVisibleChooseIncomeP = true;
      setTimeout(() => {
        this.isVisibleChooseIncome = true;
      }, 100);
    },
    /**
     * 选择月收入
     */
    chooseIncome(val) {
      this.form.salary = val;
      this.isVisibleChooseIncome = false;
      this.isVisibleChooseIncomeP = false;
    },
    /**
     * 显示选择宗教
     */
    showChooseReligion() {
      this.isVisibleChooseReligionP = true;
      setTimeout(() => {
        this.isVisibleChooseReligion = true;
      }, 100);
    },
    chooseReligion(val) {
      this.form.religion = val;
      this.isVisibleChooseReligion = false;
      this.isVisibleChooseReligionP = false;
    },
    /**
     * 显示选择社交账号类型
     */
    showChooseSocialAccountType() {
      this.isVisibleChooseSocialAccountTypeP = true;
      setTimeout(() => {
        this.isVisibleChooseSocialAccountType = true;
      }, 100);
    },
    /**
     * 选择社交账号类型
     */
    chooseSocialAccountType(val) {
      this.form.socialAccountType = val;
      this.isVisibleChooseSocialAccountType = false;
      this.isVisibleChooseSocialAccountTypeP = false;
    },
    /**
     * 获取页面数据
     */
    getData() {
      this.$api.qureyUserBaseInfo().then((res) => {
        const { status, error, data } = res;
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          const form = this.form;
          // let childrenNumber;
          // if (form.childrenNumber >= 0) {
          //   childrenNumber = this.childData.filter(item => item.value === data.childrenNumber);
          // }
          form.region = data.district;
          form.province = data.province;
          form.city = data.townCity;
          form.address = data.address;
          form.civilStatus = data.civilStatus;
          // form.childrenNumber = (childrenNumber && childrenNumber.length >= 1) ? childrenNumber[0].name : data.childrenNumber;
          form.education = data.education;
          // form.salary = data.salary;
          form.email = data.email;
          form.phone = data.phone;
          // form.religion = data.religion;
          if (form.region) {
            this.getProvinceData();
            this.getCityData();
          }
          form.socialAccountType = data.socialAccountType;
          form.socialAccount = data.socialAccount;
        }
      });
    },
    /**
     * 获取资料填写度
     */
    getInfoData() {
      this.$api.getDataIntegrity().then((res) => {
        const { status, error, data } = res;
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          const status = this.status;
          status.identity = data.USERBASEINFO === "1"; // 基本信息
          status.personal = data.USERPERSONALINFO === "1"; // 个人信息
          status.work = data.USERJOB === "1"; // 工作信息
          status.contact = data.USERCONTACT === "1"; // 联系人信息
          status.additional = data.USERCARDID === "1"; // 身份信息
          if (data.USERPERSONALINFO === "1") {
            this.readonly = true;
          }
        }
      });
    },
    /**
     * 跳转填资
     */
    goInformation(url) {
      const path = "/information/" + url;
      const instalment = this.instalment ? "true" : "false";
      this.$router.push({
        path,
        query: { productId: this.productId, instalment },
      });
    },
    /**
     * 表单提交
     */
    submitHandler() {
      if (this.disabledBtn) return
      // 个人信息页 - 提交 - 点击
      this.$buryPoint.action({
        eventName: 'personalInfo_submit_click',
        ...this.pageTrackerInfo
      });

      const form = this.form;
      if (!this.checkInput("personalInfo")) {
        this.$toast("Please complete your information");
        return;
      }
      // if (!validateEmail(form.email)) {
      //   this.$toast(this.$tc('plsInputRightEmail'));
      //   this.markInput(['email']);
      //   return;
      // }
      if (!validateMobile(form.phone)) {
        //this.$toast(this.$tc("plsInputRightMobile"));
        this.markInputNew(["phone"]);
        return;
      }
      // if ((form.socialAccountType === 'Facebook' || form.socialAccountType === 'Skype') && (!validateEmail(form.socialAccount) && !validateMobile(form.socialAccount))) {
      //   this.$toast(this.$tc('plsInputRightSocialAccount'));
      //   this.markInput(['socialAccount']);
      //   return;
      // }
      // if ((form.socialAccountType === 'Viber' || form.socialAccountType === 'WhatsApp') && !validateMobile(form.socialAccount)) {
      //   this.$toast(this.$tc('plsInputRightSocialAccount'));
      //   this.markInput(['socialAccount']);
      //   return;
      // }
      if (!validateAddress(form.address)) {
        //this.$toast(this.$tc("plsInputCorrectAddress"));
        this.markInputNew(["address"]);

        return;
      }
      const province = Province.province.filter(
        (item) => item.Province === form.province
      );
      const city = City.city.filter((item) => item.TownCity === form.city);
      const civilStatus = this.maritalData.filter(
        (item) => item.CivilStatus === form.civilStatus
      );
      // const childrenNumber = this.childData.filter(item => item.name === form.childrenNumber);
      const params = {
        district: form.region,
        province: form.province,
        provinceId: province[0].ProvinceId,
        townCity: form.city,
        townCityId: city[0].TownCityId,
        address: form.address,
        education: form.education,
        civilStatus: form.civilStatus,
        civilStatusId: civilStatus[0].CivilStatusId !== 1 ? 2 : 1,
        // salary: form.salary,
        email: form.email,
        phone: form.phone,
        // childrenNumber: childrenNumber[0].value,
        // religion: form.religion,
        childrenNumber: this.childData[0].value,
        religion: this.religionData[0],
        socialAccountType: form.socialAccountType,
        socialAccount: form.socialAccount,
      };
      this.disabledBtn = true;
      this.$api
        .addOrUpdateUserBaseInfo(params)
        .then((res) => {
          const { status, error, msg } = res;
          if ("1" === status && ("00000000" === error || "0000" === error)) {
            // 个人信息页 - 提交 - 成功
            this.$buryPoint.action({
              eventName: 'personalInfo_submit_success',
              ...this.pageTrackerInfo
            });
            this.$refs.checkFaceInfo.returnTo().catch(e => {
              this.disabledBtn = false;
            });
          } else {
            this.disabledBtn = false
            this.$toast(msg);
          }
        })
        .catch((error) => {
          this.disabledBtn = false;
        });
    },
    // 聚焦
    IdFocus(e) {
      // const params = {
      //   content: 'basic_page_second_phone_fill_start',
      //   value: '',
      // };
      // this.$hybrid.action('ee', {
      //   ...params
      // });
    },
    // 取消聚焦
    IdBlur(e) {
      this.handleBlurCheck(e, "phone");
      // const params = {
      //   content: 'basic_page_second_phone_fill_end',
      //   value: e.target.value,
      // };
      // console.warn(params);
      // this.$hybrid.action('ee', {
      //   ...params
      // });
    },
  },
  created() {
    const query = this.$route.query;
    this.productId = query.productId;
    if (query.btnType && query.btnType === "save") {
      // 按钮是下一步，还是保存
      this.btnName = this.$t("save");
    }
    // this.readonly = (query.readonly === 'true');
    this.instalment = query.instalment === "true";
    this.regionData = Region.region;
    this.getInfoData();
    this.getData();
  },
  beforeDestroy () {
    this.pageEndAction()
  },
  mounted () {
    this.pageStartAction()
    // 个人信息页 - 页面 - 曝光
    this.$buryPoint.action({
      eventName: 'personalInfo_page_show',
      ...this.pageTrackerInfo
    });
  }
};
